#include "command.h"

void handler_mkdir(char *user_name, data *msg, int net_fd, MYSQL *mysql){

    // 接收文件夹名
    char floder_name[1024] = {0};
    bzero(floder_name, sizeof(floder_name));
    ssize_t received = recv(net_fd, floder_name, sizeof(floder_name), MSG_WAITALL);

    // 要创建的文件夹路径
    char floder_path[3072] = {0};
    strncat(floder_path, msg->args, sizeof(floder_path) - strlen(floder_path) - 1);
    if (strlen(floder_path) > 1){
        strncat(floder_path, "/", sizeof(floder_path) - strlen(floder_path) - 1);
    }
    strncat(floder_path, floder_name, sizeof(floder_path) - strlen(floder_path) - 1);

    // 查询该文件夹是否存在
    char sql_buf[8192] = {0};
    sprintf(sql_buf, "SELECT COUNT(*) FROM file WHERE user_id = \
                        (SELECT user_id FROM user WHERE user_name = '%s') \
                        AND file_path = '%s' \
                        AND file_name = '%s' \
	                    AND file_type = 1 \
                        AND is_deleted = 0;",
            user_name, floder_path, floder_name);
    mysql_query(mysql, sql_buf);
    MYSQL_RES *result = mysql_store_result(mysql);

    int ret = 0; // 用于存储查询结果的变量
    MYSQL_ROW row;
    if ((row = mysql_fetch_row(result))){
        // 查询结果只有一列，且该列为 int 类型
        ret = atoi(row[0]); // 将结果转换为 int 类型
    }
    mysql_free_result(result);

    // 返还结果
    ssize_t sent = send(net_fd, &ret, sizeof(int), 0);
    if (sent < 0){
        perror("send failed in handler_send_ls"); // 处理错误...
    }

    // 对不同结果进行处理
    // ret == 1 -> 文件夹存在，不做处理
    // ret == 0 -> 文件夹不存在，创建
    if (ret == 1){
        // 存在
        // 服务端不做处理，客户端报错
    }else{
        // 文件夹不存在，创建
        bzero(sql_buf, sizeof(sql_buf));
        sprintf(sql_buf, "INSERT INTO file (file_name, user_id, file_path, file_type, is_deleted, father_id) \
                      VALUES ( \
                      '%s', \
                      (SELECT user_id FROM user WHERE user_name = '%s' LIMIT 1), \
                      '%s', \
                      1, \
                      0, \
                      (SELECT f.file_id FROM file f \
                      WHERE f.file_path = '%s' \
                      AND f.is_deleted = 0 \
                      AND f.user_id = (SELECT user_id FROM user WHERE user_name = '%s') ) );",
                floder_name, user_name, floder_path, msg->args, user_name);
        mysql_query(mysql, sql_buf);
    }

}